#include "ofxJSTuioClient.h"
#include "js/ofxJSTuioClient.cpp"

// ----------------------------------------------------------------
// ofxJSTuioClient
// ----------------------------------------------------------------
ofxJSTuioClient::ofxJSTuioClient(JSObject* pJSListener)
{
	mp_jsListener = pJSListener;

	ofAddListener(m_tuio.cursorAdded,this,&ofxJSTuioClient::tuioAdded);
	ofAddListener(m_tuio.cursorRemoved,this,&ofxJSTuioClient::tuioRemoved);
	ofAddListener(m_tuio.cursorUpdated,this,&ofxJSTuioClient::tuioUpdated);
}

// ----------------------------------------------------------------
// ~ofxJSTuioClient
// ----------------------------------------------------------------
ofxJSTuioClient::~ofxJSTuioClient()
{
}

//--------------------------------------------------------------
void ofxJSTuioClient::initialize()
{
	ofxJSTuioClient::JSInit(ofxJSGetContext(), ofxJSGetGlobalObj());
}

//--------------------------------------------------------------
void ofxJSTuioClient::finalize()
{
}

// ----------------------------------------------------------------
void ofxJSTuioClient::tuioAdded	(ofxTuioCursor & tuioCursor)
{
	// TODO : implement better the transmission of information (struct tuioCursor)
	// for the moment, only (id,x,y) is set in js
	if (mp_jsListener)
	{
		ofxJSValue retVal;
		ofxJSValue args[3];
		args[0] = int_TO_ofxJSValue(tuioCursor.getFingerId());
		args[1] = float_TO_ofxJSValue(tuioCursor.getX());
		args[2] = float_TO_ofxJSValue(tuioCursor.getY());

		ofxJSCallFunctionNameObject_IfExists(mp_jsListener, "tuioAdded", args, 3, retVal);
	}
}

// ----------------------------------------------------------------
void ofxJSTuioClient::tuioRemoved	(ofxTuioCursor & tuioCursor)
{
	if (mp_jsListener)
	{
		ofxJSValue retVal;
		ofxJSValue args[1];
		args[0] = int_TO_ofxJSValue(tuioCursor.getFingerId());

		ofxJSCallFunctionNameObject_IfExists(mp_jsListener, "tuioRemoved", args, 1, retVal);
	}
}

// ----------------------------------------------------------------
void ofxJSTuioClient::tuioUpdated	(ofxTuioCursor & tuioCursor)
{
	if (mp_jsListener)
	{
		ofxJSValue retVal;
		ofxJSValue args[3];
		args[0] = int_TO_ofxJSValue(tuioCursor.getFingerId());
		args[1] = float_TO_ofxJSValue(tuioCursor.getX());
		args[2] = float_TO_ofxJSValue(tuioCursor.getY());

		ofxJSCallFunctionNameObject_IfExists(mp_jsListener, "tuioUpdated", args, 3, retVal);
	}
}

//--------------------------------------------------------------
OFX_INST_DEFINE_JSFUNC_1(ofxJSTuioClient,start,int,m_tuio)
//--------------------------------------------------------------
OFX_INST_DEFINE_JSFUNC_0(ofxJSTuioClient,start,m_tuio)
//--------------------------------------------------------------
OFX_INST_DEFINE_JSFUNC_0(ofxJSTuioClient,getMessage,m_tuio)
//--------------------------------------------------------------
OFX_INST_DEFINE_JSFUNC_0(ofxJSTuioClient,drawCursors,m_tuio)
